package com.lemon.cloud.author.oauth2.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * @author lemon
 * @version 1.0
 * @description: TODO
 * @date Create by lemon on 2019-08-17 22:35
 */
@Slf4j
@Configuration
public class WebResponseExceptionTranslateConfig {
    /**
     * @param
     * @return
     * @description 自定义登录或者鉴权失败时的返回信息
     * @author lemon
     * @date 2019-08-17 22:35
     */
    @Bean
    public WebResponseExceptionTranslator webResponseExceptionTranslator() {
        return new DefaultWebResponseExceptionTranslator() {
            @Override
            public ResponseEntity translate(Exception e) throws Exception {
                ResponseEntity responseEntity = super.translate(e);
                OAuth2Exception body = (OAuth2Exception) responseEntity.getBody();
                HttpHeaders headers = new HttpHeaders();
                headers.setAll(responseEntity.getHeaders().toSingleValueMap());

                // do something with header or response
                if (400 == responseEntity.getStatusCode().value()) {
                    if ("Bad credentials".equals(body.getMessage())) {
                        return new ResponseEntity(new RuntimeException("400 您输入的用户名或密码错误", body), headers, HttpStatus.OK);
                    }
                }

                return new ResponseEntity(body, headers, responseEntity.getStatusCode());
            }
        };
    }
}
